package com.common.account.granter;

import com.common.account.service.CustomUserDetailsService;
import com.common.account.service.IAuUserService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 验证码登录
 *
 * @author wangguochao
 */
public class PawVerifyTokenGranter extends AbstractTokenGranter {
    private static final String GRANT_TYPE = "verify";
    protected CustomUserDetailsService userDetailsService;
    protected IAuUserService iAuUserService;

    public PawVerifyTokenGranter(CustomUserDetailsService customUserDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.userDetailsService = customUserDetailsService;

    }

    public PawVerifyTokenGranter(CustomUserDetailsService customUserDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IAuUserService iAuUserService) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.userDetailsService = customUserDetailsService;
        this.iAuUserService = iAuUserService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        UserDetails details = userDetailsService.loadUserByPawAndVerify(parameters);
        Authentication userAuth = new UsernamePasswordAuthenticationToken(details,
                details.getPassword(), details.getAuthorities());
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuth);
        authentication.setAuthenticated(true);
        return authentication;
    }
}
